// pages/score/score.js
Page({
    data: {
      gradeID: '', // 当前打分的ID
      descImgUrl:"",//描述图片
      haveDescImg:true,
      imgUrl:'../../imgs/addImg.png',//自定义分享图
      needPersonalInformation:false,//是否需要个人信息
      gradeCreate:"",//创建日期
      shareGroupImgUrl:"../../imgs/share.png",//icon
      shareImgUrl:"",
      onlyGroupMember:0,//只允许群成员投票
      gradeTitle: '', // 当前打分的标题
      gradeDesc: '11111111', // 当前打分的补充描述
      endDate: '', // 当前打分的截止日期
      isAnonymous: false, // 当前打分是否匿名
      isExpired: false, // 当前打分是否已过期
      alreadyGraded:false, // 当前用户是否已经打分
      optionDesc:'',
      gradeStatus:[],
      buttonDisable:false,
      userImgUrl:"../../imgs/login.png",//用户头像
      nickname:"未登录",
      isLogin:false,
      gradeAvatarUrls:[], //所有参与到该投票的用户头像,
      textName:"",   //输入的姓名
      textPhone:"",  //输入的手机号码
      isInput:false,  //是否输入了个人信息
      isShowModal:false, //是否显示过弹窗
      regJudge: false,
      createrOpenId:"",//发起人的openid
      isCreater: false,
      blockHeight:0,//区块高度
      transactionId:0,//交易ID
      CreatedOrJoined:1,//从创建页面进入or从参与页面进入
      score:0,//分数
      sumUser:0,
      sumScore:0
    },
    onLoad(options) {
      const gradeID = options.gradeID // 通过页面路径参数获取投票ID
      const CreatedOrJoined = options.CreatedOrJoined
      console.log('gradeID',gradeID)
      console.log('CreatedOrJoined',CreatedOrJoined)
      this.setData({
        gradeID:gradeID,
        CreatedOrJoined:CreatedOrJoined
      })
      this.getGradeStatusFromBlockchain(gradeID)
      this.getGradeDataFromBlockchain(gradeID)
    //   this.getVoteStatusFromBlockchainAndLocal(this.data.voteID) 
    //   this.getVoteDataFromBlockchainAndLocal(this.data.voteID) 
      this.checkLogin()
      this.queryBlockInfo(this.data.gradeID)
      // if (wx.getStorageSync('userid') != ''){
      //   //console.log(userid)
      //   let userid = wx.getStorageSync('userid')
      //     this.setData({
      //       userId: userid
      //     })
      // }
      wx.showShareMenu({
        withShareTicket: true
      })
    },
    onPullDownRefresh: function () {
      this.getVoteStatusFromBlockchain(gradeID)
      this.getVoteDataFromBlockchain(gradeID)
    //   this.getVoteStatusFromBlockchainAndLocal(this.data.voteID) // 从服务端获取是否已经投票
    //   this.getVoteDataFromBlockchainAndLocal(this.data.voteID) // 从服务端获取投票情况
    },
    checkExpired(endDate) {
      const now = new Date();
      const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
      const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
      const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
      const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number
  
      const endDateArray2 = endDate[1].split(':') 
      const endHour = Number(endDateArray2[0]) 
      const endMinute = Number(endDateArray2[1]) 
      const endSecond = Number(endDateArray2[2]) 
  
      const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute,endSecond);
      console.log('now',now)
      console.log('time',time)
      if(now>time){
        console.log('过期啦')
        return true;
      }else{
        console.log('没过期啦')
        return false;
      }
    },
    onScoreInputChange(e) {
        this.setData({
          score: e.detail.value
        })
      },
    onTapGrade() {
      let that = this 
            //console.log(this.data.buttonDisable)
      if(that.data.isLogin===false){
        wx.login({
          success: function(login_res) {
          that.setData({
              code:login_res.code,
              userid:login_res.userid
          })
          wx.setStorageSync('code', login_res.code)
          wx.setStorageSync('userid', login_res.userid)
          }
        })
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '您还未登录',
          content: '请先登录再进行操作',
          confirmText:'立即登录',
          cancelText:'暂不登录',
          showCancel: false,
          success:function(res){
            if(res.confirm){
              that.userLogin()
              that.checkLogin()
            }
          }
        })
        return
      }  
      //当已经显示过弹窗且输入了个人信息以后，这个情况才会过掉
      if((that.data.isShowModal===false) && (that.data.isInput===false) &&(that.data.needPersonalInformation===true)){
        that.setData({
          isShowModal:true  
        })
        return
      }
  
      //const msg = this.checkFormValid() //对选择的内容进行检查
      //单选
     

      if(!(/^(100|[1-9]?[0-9]?)$/.test(this.data.score))){
          wx.showToast({
            title: '请输入百分制整数',
            icon:'none',
            duration: 2000
          })
          return
      }


      

      //若已经逾期，则不能投票出去
      const endDateArray =  that.data.endDate.split(' ') // 将字符串分割成字符数组，分隔符为-
      if( that.checkExpired(endDateArray)){
        wx.showToast({
          title: '已逾期',
          icon:'error',
          duration: 2000
        })
        return     
      }
  
  
       // 校验通过时后面的内容才会被执行
       if(wx.getStorageSync('code') == '') {
        wx.login({
          success: function(login_res) {
            that.setData({
              code:login_res.code
            })
            wx.setStorageSync('code', login_res.code)
          }
        })
      }
        const _this =  that // 在API接口中的函数中，this会被改变，因此需要提前获取this的值到_this中
        const now = new Date()
        const nowYear = now.getFullYear()
        const nowMonth = (now.getMonth() + 1)>=10?now.getMonth() + 1:'0'+(now.getMonth() + 1)
        const nowDay = now.getDate()>=10?now.getDate():'0'+now.getDate()
        
        

        _this.setData({
          buttonDisable:true
        })
        wx.showLoading({
          title: '加载中',
          mask:true
        })
        wx.request({
          //url: 'https://www.intohash.com/vote_backend/vote_user/vote',
          url: 'http://localhost:8010/vote_backend/user_grade/grade',
          method:"POST",
          data: {
            "currentTime":nowYear+'-'+nowMonth+'-'+nowDay,
            "score": _this.data.score,
            "userId": wx.getStorageSync('userid'),
            "gradeId": _this.data.gradeID,
          },
          success:function(res) {
            console.log('打分成功')
            console.log(res)
            _this.getGradeStatusFromBlockchain(_this.data.gradeID) // 从服务端获取是否已经投票
            _this.getGradeDataFromBlockchain(_this.data.gradeID) // 从服务端获取投票情况
     
            wx.hideLoading()
  
            _this.queryBlockInfo(_this.data.gradeID)
          },
          fail:function(res) {
            
            wx.hideLoading()
       
            console.log(res)
            wx.showToast({
              title: '打分失败',
              icon: 'none'
            })
          }
        })
      
    }, 
  
    getGradeStatusFromBlockchain(gradeID) {
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote_user/queryHaveVoted/'+wx.getStorageSync('userid')+'/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/user_grade/queryHaveGraded/'+wx.getStorageSync('userid')+'/'+gradeID ,
        method:'GET',
        success:function (res) {
          console.log('查询投票')
          console.log(res)  // 控制台输出服务端返回的结果
          that.setData({
            alreadyGraded:res.data.data.haveGraded,
          })
        },
        fail: function(res) {
          console.error(res)  // 如果出现异常，控制台输出异常详情
          wx.showToast({  // 调用提示框API提示用户获取数据失败
            title: '获取投票数据失败',
            icon: 'none'
          })
        }
      })
    },
     getGradeDataFromBlockchain(gradeID) {
      let that = this
      wx.request({
        //url: 'https://www.intohash.com/vote_backend/vote/queryVoteInfo/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/grade/queryGradeInfo/'+this.data.gradeID,
        method:'GET',
        success:function(res) {
          const ret = res.data.data
          console.log('投票信息')
          console.log(ret)
          console.log(that.data)
          const endDateArray = ret.rule.endDate.split(' ') // 将字符串分割成字符数组，分隔符为-
          const isExpired = that.checkExpired(endDateArray) // 检查投票是否已经过期
        
          let gradeShareImgurl = ret.shareImgUrl;
          if (gradeShareImgurl == '../../imgs/addImg.png') {
            gradeShareImgurl = ''
          }
          that.setData({
            gradeTitle:ret.title,
            gradeDesc:ret.gradeDesc,
            endDate:ret.rule.endDate,
            needPersonalInformation:ret.rule.needPersonalInformation?true:false,
            gradeCreate:ret.gradeCreate,
            isExpired:isExpired,
            totalGradeCount:ret.sumUser,
            onlyGroupMember:ret.rule.onlyGroupMember,
            descImgUrl:ret.descImgUrl,
            shareImgUrl:gradeShareImgurl,
            isAnonymous:ret.rule.isAnonymous,
            gradeAvatarUrls:ret.gradeAvatarUrls,
            createrOpenId:ret.openId,
            sumUser:ret.sumUser,
            sumScore:ret.sumScore
          })
          if(that.data.descImgUrl==="../../imgs/addDescImg.png"){
          that.setData({
            haveDsecImg:false
          })
        }
        if(isExpired){
          that.setData({
            alreadyGraded:true
          })
        }
        if(that.data.alreadyGraded===true){
          that.setData({
            textName:wx.getStorageSync('name'),
            textPhone:wx.getStorageSync('Phone'),
            isInput:wx.getStorageSync('isInput')
          })
        }
        if(that.data.createrOpenId===wx.getStorageSync('userid')){
          that.setData({
            isCreater:true
          })
        }
        },
        fail:function(res) {
        }
  
      })
      //return that.data.allowGroupVote
    },
    onShareAppMessage: function (res) {
      console.log("转发");
      return {
      title: '邀请你参与打分',
      path: '/pages/score/score?gradeID=' + this.data.gradeID,
      imageUrl: this.data.shareImgUrl,
      success(res){
        console.log('成功')
        if(that.data.onlyGroupMember!=0) wx.hideShareMenu()
      }
      }
    },
    previewImage() {
      wx.previewImage({
        urls: [this.data.descImgUrl],
      })
  },
    
    
    checkLogin:function(){
      if (wx.getStorageSync('userinfo') != '') {
        //console.log(userinfo)
        let userinfo = wx.getStorageSync('userinfo')
          this.setData({
            nickname: userinfo.nickName,
            userImgUrl: userinfo.avatarUrl,
            isLogin:true
          })
      }
      else{
        this.setData({
          isLogin:false
        })
      }
    },
    userLogin : function() {
      if (wx.getStorageSync('userid') == '') {
          let that = this
          wx.getUserProfile({
              desc:'请求用户授权',
              success: function(info_res) {
                console.log(info_res)
                let userinfo = info_res.userInfo
                wx.setStorageSync('userinfo', userinfo)
                that.setData({
                  nickname: userinfo.nickName,
                  userImgUrl: userinfo.avatarUrl,
                  isLogin:true
              })
                // 2. 小程序通过wx.request()发送code到开发者服务器
                wx.request({
                  //url: 'https://www.intohash.com/vote_backend/user/login',
                  url: 'http://localhost:8010/vote_backend/user/login',
                  method: 'POST',
                  data: {
                    authTyoe: 1 ,
                    code: wx.getStorageSync('code'), //临时登录凭证
                    encrypteData: info_res.encryptedData, //用户敏感信息
                    iv: info_res.iv, //解密算法的向量
                    rawData: info_res.rawData, //用户非敏感信息
                    signature: info_res.signature //签名   
                  },
                  success: function(res) {
                    console.log('验证成功')
                    console.log(res)
                    wx.setStorageSync('skey', res.data.data.sKey)
                    wx.setStorageSync('userid', res.data.data.openid)
                    wx.request({
                      //url: 'https://www.intohash.com/vote_backend/user/qrCode/'+res.data.data.openid,
                      url: 'http://localhost:8010/vote_backend/user/qrCode/'+res.data.data.openid,
                      method: "GET",
                      success:function(res) {
                        wx.setStorageSync('qrCodeUrl', res.data.data)
                        that.setData({
                          qrCodeUrl: res.data.data
                        })
                      }
                    })
                    wx.redirectTo({       // 自动跳转到参与投票页面
                      url: '/pages/score/score?scoreID=' + that.data.scoreID,
                    })
                  },
                  fail: function(error) {
                    //调用服务端登录接口失败
                    wx.showToast({
                      title: '登陆失败!',
                      duration: 2000,
                    })
                    console.log(error);
                  }
                })
              }
            })
      }
    },
  
    wish_put1:function(e){
      this.setData({
        textName:e.detail.value
      })
      console.log('textname',this.data.textName)
    },
    wish_put2:function(e){
      this.setData({
        textPhone:e.detail.value
      })
      console.log('text',this.data.textPhone)
    },
    confirm(){
      let curPhone = this.data.textPhone
      console.log("qqq")
      console.log(curPhone)
      if (!(/^1[34578]\d{9}$/.test(curPhone))) {
        wx.showToast({
               title: '手机号格式有误',
              icon:'error',
               duration: 2000
              })
        this.setData({
         regJudge: false
        })
        if (curPhone.length >= 11) {
              wx.showToast({
               title: '手机号格式有误',
               icon:'error',
               duration: 2000
              })
             }
            } else {
             this.setData({
            regJudge: true
             })}
             console.log('验证成功', this.data.regJudge)
        if( this.data.regJudge===true){
          this.setData({
            isInput:true,
            isShowModal:false,
          })
          wx.setStorageSync('name', this.data.textName)
          wx.setStorageSync('Phone', this.data.textPhone)
          wx.setStorageSync('isInput', this.data.isInput)
        }
  
    },
    back(){
      //如果点击了返回，就当还没有显示过弹窗 
      this.setData({
        isShowModal:false,
      })
    },

    queryBlockInfo(gradeid){
      console.log("gradeid",gradeid)
      console.log("gradeID",this.data.gradeID)
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote/queryVoteDetail/'+that.data.voteID,
        url: 'http://localhost:8010/vote_backend/user_grade/queryGradeDetail/'+that.data.gradeID,
        method:'GET',
        data: {
          "userId": wx.getStorageSync('userid'),
          "gradeId": that.data.gradeID
        },
        success:function (res) {
          console.log('查询区块链信息成功')
          console.log(res)  // 控制台输出服务端返回的结果
          that.setData({
            blockHeight:res.data.data.gradeDetails[0].voteBlockChain.blockHeight,
            transactionId:res.data.data.gradeDetails[0].voteBlockChain.transactionId
          })
          wx.setStorageSync('blockHeight', res.data.data.gradeDetails[0].voteBlockChain.blockHeight)
          wx.setStorageSync('transactionId', res.data.data.gradeDetails[0].voteBlockChain.transactionId)
        },
        fail:function(res) {
          console.log(res)
          wx.showToast({
            title: '查询区块链信息失败',
            icon: 'none'
          })
          }
      })
    },
   
  
  })